import { store } from "@/store";
import { defineStore } from "pinia";
import MerchantApi, {
  type MerchantListQuery,
  type MerchantType,
  type MerchantForm,
} from "@/api/merchant/merchant";

export const useMerchantStore = defineStore("merchant", () => {
  const list = ref<MerchantType[]>([]);

  const totalCount = ref(0);

  const totalPage = ref(0);

  const loading = reactive({
    list: false,
    create: false,
    update: false,
    delete: false,
    examine: false,
  });

  async function fetchMerchantList(params: MerchantListQuery) {
    loading.list = true;
    const response = await MerchantApi.getMerchantList(params);
    loading.list = false;
    if (response) {
      list.value = response.records;
      totalCount.value = response.total_count;
      totalPage.value = response.total_page;
    }
  }

  async function fetchCreateMerchant(data: Partial<MerchantForm>) {
    loading.create = true;
    try {
      await MerchantApi.addMerchant(data);
      loading.create = false;
    } catch (error) {
      console.error("Error creating subject:", error);
      loading.create = false;
    }
  }

  async function fetchUpdateMerchant(data: Partial<MerchantForm>) {
    loading.update = true;
    try {
      await MerchantApi.updateMerchant(data);
      loading.update = false;
    } catch (error) {
      console.error("Error updating subject:", error);
      loading.update = false;
    }
  }

  async function fetchDeleteMerchant(id: number) {
    loading.delete = true;
    await MerchantApi.deleteMerchant(id);
    loading.delete = false;
  }

  async function fetchExamineMerchant(data: any) {
    loading.examine = true;
    try {
      await MerchantApi.examineMerchant(data);
      loading.examine = false;
    } catch (error) {
      console.error("Error", error);
      loading.examine = false;
    }
  }

  return {
    list,
    totalCount,
    totalPage,
    loading,
    fetchMerchantList,
    fetchCreateMerchant,
    fetchUpdateMerchant,
    fetchDeleteMerchant,
    fetchExamineMerchant,
  };
});

export const useMerchantStoreHook = () => {
  return useMerchantStore(store);
};
